package com.xbongbong.crm.perform.query.detail;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmDetailTopInfoService;
import com.xbongbong.crm.help.FineClueHelp;
import com.xbongbong.crm.service.permission.CompetitorPermissionServiceImpl;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.DetailTitlePojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.service.DetailTabConfigService;
import com.xbongbong.paas.service.LinkListService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.pro.appdetail.pojo.MobileDetailMoneyItemPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailScriptPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailSpecialInfoPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusPojo;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.vo.FormDataDetailVO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.paas.service.BusinessButtonService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.CompetitorErrorCodeEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.util.NameUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author: yingjf
 * @date: 2022/9/15 15:50
 * @description:
 */
@Service("competitorDetailTopInfoServiceImpl")
public class CompetitorDetailTopInfoServiceImpl extends AbstractCrmDetailTopInfoService {

    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private BusinessButtonService businessButtonService;
    @Resource
    private LinkListService linkListService;
    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private CompetitorPermissionServiceImpl competitorPermissionService;
    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private DetailTabConfigService detailTabConfigService;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private FineClueHelp fineClueHelp;
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.COMPETITOR.getCode());
    }

    @Override
    public List<MobileDetailMoneyItemPojo> getMobileDetailMoneyInfo(Integer distributorMark, String corpid, String userId, Integer businessType, Integer subBusinessType, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        return new ArrayList<>();
    }

    @Override
    public JSONArray getBottomBlockInfo(String corpid, String userId, Integer businessType, PaasFormEntityExt formEntity, Long dataId, JSONObject data, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt entityExt, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        return null;
    }

    @Override
    public List<MobileDetailScriptPojo> getDetailShowScript(Integer businessType, UserVO loginUser, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        return new ArrayList<>();
    }

    @Override
    public MobileDetailStatusPojo getDetailShowStatus(Integer businessType, JSONObject data) throws XbbException {
        return null;
    }

    @Override
    public Map<String, Object> getDetailShowOperation(String corpid, String userId, Integer businessType, Long dataId, JSONObject data) throws XbbException {
        return new HashMap<>(BasicConstant.DEFAULT_ACCURACY);
    }

    @Override
    public JSONObject returnSaasObject(String corpid, Integer businessType, UserVO userVO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        JSONObject saasReturnObj = new JSONObject();
        //客户动态显示与否
        saasReturnObj.put(StringConstant.DYNAMIC, true);
        //动态名称
        saasReturnObj.put(StringConstant.DYNAMICNAME, I18nMessageUtil.getMessage(I18nStringConstant.COMPETITOR_DYNAMIC));
        return saasReturnObj;
    }

    @Override
    public List<TopPermissionsPoJo> dingtalkHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        String corpid = formEntity.getCorpid();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer businessType = formEntity.getBusinessType();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, userVO.getPermSet());
        List<String> aliasIn = new ArrayList<>();
        workFlowEnumList.forEach(item -> aliasIn.add(XbbRefTypeEnum.getByCode(item.getBusinessType()).getAlias()));
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);

        List<TopPermissionsPoJo> topPermissions = businessButtonService.dingtalkDetailCommon(userVO, formEntity, explainMap, formData);
        List<LinkListPojo> linkList = formEntity.getLinkListList();
        topPermissions.addAll(linkListService.getDingtalkCommonButton(linkList, formData.getDel(), userVO, formData.getAppId(), formData.getFormId(), businessType, formEntity.getSaasMark(), corpid));

        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
            BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
            if (Objects.equals(workFlowEnum.getFormRelation(), BasicConstant.ONE)) {
                NameUtil.changeValue(paasBusinessTypeToName, topPermissionsPoJo);
            }
            topPermissionsPoJo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(workFlowEnum.getBusinessType()));
            topPermissionsPoJo.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
            topPermissions.add(topPermissionsPoJo);
        }
        return topPermissions;
    }

    @Override
    public JSONArray getSecondTitleList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formDataDetailDTO.getBusinessType();
        Long formId = formData.getFormId();
        List<SummaryDataPoJo> summaryList = getSummaryList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        specialTransferKeyToShowValue(corpid, summaryList, businessType,data, formId);
        JSONArray secondTitle = getSecondTitleList(summaryList, data, formDataDetailDTO.getCorpid(), formEntity.getId());
        return secondTitle;
    }

    @Override
    public JSONArray getTagList(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        Integer businessType = formEntity.getBusinessType();
        Long dataId = formData.getId();
        String userId = formDataDetailDTO.getUserId();
        Long formId = formData.getFormId();
        List<SummaryDataPoJo> labelsList = getLabelList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        return getTags(labelsList, corpid, businessType, dataId, userId);
    }

    @Override
    public String getTitle(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt formData, PaasFormEntityExt formEntity, List<FieldAttrEntity> list, Map<String, FieldAttrEntity> explainMap, JSONObject data) throws XbbException {
        List<FormTitlePoJo> formTitleList = getTitleList(formDataDetailDTO, formData, formEntity, list, explainMap, data);
        return TitleUtil.getWebTitle(formTitleList);
    }

    @Override
    public DetailTitlePojo handleDetailFocus(FormDataDetailDTO formDataDetailDTO, Integer businessType, PaasFormDataEntityExt paasFormDataEntityExt, String userId) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        DetailTitlePojo detailTitlePojo = new DetailTitlePojo();
        String pid = getPid(formDataDetailDTO, corpid, paasFormDataEntityExt);
        detailTitlePojo.setPid(pid);
        return detailTitlePojo;
    }



    @Override
    public void checkPermission(PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, UserVO loginUser, Integer subBusinessType) throws XbbException {

        Boolean isUltimate= packageHelp.isUltimateWithFeeType(formEntity.getCorpid());
        if(!isUltimate){
            // 非旗舰版不允许查看详情
            throw new XbbException(CompetitorErrorCodeEnum.API_ERROR_330003.getCode(), CompetitorErrorCodeEnum.API_ERROR_330003.getMsg());
        }

        if (loginUser.isMaxDataPermission()){
            return ;
        }
        Integer flowStatus = paasFormDataEntityExt.getFlowStatus();
        Long menuId = formEntity.getMenuId();
        Integer saasMark = formEntity.getSaasMark();
        Integer businessType = formEntity.getBusinessType();

        // 查看权限校验
        verifyQueryPermission(businessType, loginUser,saasMark ,menuId ,flowStatus);
        //团队权限&共享权限校验
        competitorPermissionService.checkPermission(formEntity, paasFormDataEntityExt, loginUser, subBusinessType);

    }

    @Override
    public JSONObject analysisData(PaasFormDataEntityExt paasFormDataEntityExt, HandlerExplainDTO handlerExplainDTO, HandlerExplainVO handlerExplainVO) throws XbbException {
        Long formId = paasFormDataEntityExt.getFormId();
        List<FieldAttrEntity> list = handlerExplainVO.getHeadList();
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(list.size());
        Integer businessType = handlerExplainDTO.getBusinessType();
        String corpid = handlerExplainDTO.getCorpid();
        list.forEach(item->explainMap.put(item.getAttr(), item));

        ParseSingleRowDataVO parseSingleRowDataVO = commonAnalysisData(paasFormDataEntityExt, handlerExplainDTO, handlerExplainVO, list, explainMap);
        JSONObject data = parseSingleRowDataVO.getResult();
        //处理千分位
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        formDataGetVO.setData(data);
        formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO, list, false);
        return data;
    }

    @Override
    public List<WorkFlowPojo> webHandleDetailWorkFlow(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt formData) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Set<String> permSet = userVO.getPermSet();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermission(businessType, permSet);
        List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
        String corpid = userVO.getCorpid();
        // 获取销售机会菜单
        PaasMenuEntity salesOpportunityMenu = paasMenuModel.getByAlias(XbbRefTypeEnum.SALES_OPPORTUNITY.getAlias(), corpid);
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 获取对应businessType的alias
        List<String> aliasIn = new ArrayList<>();
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            if (Objects.isNull(workFlowEnum.getBusinessType())) {
                continue;
            }
            aliasIn.add(XbbRefTypeEnum.getByCode(workFlowEnum.getBusinessType()).getAlias());
        }
        param.put("corpid", corpid);
        param.put("aliasIn", aliasIn);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        List<PaasMenuEntity> paasMenuEntities = paasMenuModel.findEntitys(param);
        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        paasMenuEntities.forEach(item-> paasBusinessTypeToName.put(XbbRefTypeEnum.getByAlias(item.getAlias()).getCode(),item.getName()));
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            WorkFlowPojo workFlowPojo = new WorkFlowPojo();
            BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
            NameUtil.changeValue(paasBusinessTypeToName, workFlowPojo);
            if(Objects.equals(workFlowEnum,WorkFlowEnum.COMPETITOR_LINK_OPPORTUNITY)){
                workFlowPojo.setValue(String.format(I18nMessageUtil.getMessage(I18nStringConstant.LINK_SOMETHING), salesOpportunityMenu.getName()));
            }
            workFlowPojoList.add(workFlowPojo);
        }
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        workFlowPojoList.addAll(linkListService.getCommonButton(linkList, formData.getDel(), handelDetailPojo.getLoginUser(), formData.getAppId(), formData.getFormId(), handelDetailPojo.getBusinessType(), formEntity.getSaasMark(), corpid));
        return workFlowPojoList;
    }

    @Override
    public List<DetailTabPojo> handleDetailTab(HandelDetailPojo handelDetailPojo, PaasFormEntityExt formEntity, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap, HandlerExplainVO handlerExplainVO, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        UserVO userVO = handelDetailPojo.getLoginUser();
        List<DetailTabPojo> tabPojoList = new ArrayList<>();
        String corpid = paasFormDataEntityExt.getCorpid();
        String userId = userVO.getUserId();
        List<BusinessDetailTabEnum> tabEnumList;
        String platFormEnum = handlerExplainDTO.getPlatform();
        if (Objects.equals(platFormEnum, PlatFormEnum.WEB.getValue())) {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermission(businessType, userVO.getPermSet());
        } else {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, userVO.getPermSet());
        }

        // 获取对应businessType的alias
        List<String> aliasIn = BusinessDetailTabEnum.getAliasIn(tabEnumList);

        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = paasMenuModel.getMenuNameByAlias(aliasIn, corpid, businessType);

        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        formDataFormExplainHelper.getUserIdMap(Collections.singletonList(paasFormDataEntityExt.getDataId()),corpid,businessType,false,mainUserMap,coUserMap);

        // 当前数据的创建人、负责人、协同人、当前操作人
        handlerExplainDTO.setLoginUser(userVO);
        handlerExplainDTO.setUserId(userId);
        handlerExplainDTO.setOwnerId(mainUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCoUserId(coUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());

        for (BusinessDetailTabEnum tabEnum : tabEnumList) {
            DetailTabPojo detailTabPojo = new DetailTabPojo();
            BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
            changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
            if(Objects.equals(tabEnum,BusinessDetailTabEnum.COMPETITOR_LINKED_OPPORTUNITY)){
                detailTabPojo.setName(String.format(I18nMessageUtil.getMessage(I18nStringConstant.LINK_SOMETHING), paasBusinessTypeToName.get(tabEnum.getFormBusinessType())));
            }
            detailTabPojo.setAttr(detailTabPojo.getKey());
            tabPojoList.add(detailTabPojo);
        }
        handleTeamTab(tabPojoList, explainMap);
        List<LinkListPojo> linkList = JSONArray.parseArray(formEntity.getAssociationList(), LinkListPojo.class);
        handlerExplainVO.setAppId(formEntity.getAppId());
        handlerExplainVO.setFormId(formEntity.getId());
        // 公共tab
        tabPojoList.addAll(linkListService.commonTab(corpid, userVO, handlerExplainVO, handlerExplainDTO, businessType, paasFormDataEntityExt.getDel(), linkList));
        // tab排序
        tabPojoList = detailTabConfigService.handleDetailTabSort(userVO.getUserId(), corpid, handlerExplainVO.getFormId(), businessType, tabPojoList);
        return tabPojoList;
    }

    @Override
    public void returnVO(PaasFormEntityExt formEntity, PaasFormDataEntityExt formData, MobileFormCommonDetailVO mobileFormCommonDetailVO, String userId) throws XbbException {
        mobileFormCommonDetailVO.setHasOuterLinkShare(setOuterLinkShare(formEntity.getCorpid(), formEntity.getId()));
        mobileFormCommonDetailVO.setDistributorMark(formEntity.getDistributorMark());
        mobileFormCommonDetailVO.setPaasFormEntity(formEntity);
        //判断工商查询能否使用
        if ( fineClueHelp.isFineClueByCorpid(formData.getCorpid(), XbbRefTypeEnum.COMPETITOR.getCode(), formEntity.getDistributorMark())) {
            mobileFormCommonDetailVO.setIsFineClue(1);
        }
    }

    @Override
    protected void setFormEntity(FormDataDetailDTO formDataDetailDTO, PaasFormEntityExt form, FormDataDetailVO formDataDetailVO) {
        formDataDetailVO.setPaasFormEntityExt(form);
        //判断工商查询能否使用
        if ( fineClueHelp.isFineClueByCorpid(formDataDetailDTO.getCorpid(), XbbRefTypeEnum.COMPETITOR.getCode(), formDataDetailDTO.getDistributorMark())) {
            formDataDetailVO.setIsFineClue(1);
        }
    }

    @Override
    public MobileDetailSpecialInfoPojo getMobileDetailSpecialInfo(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        String corpid = formDataDetailDTO.getCorpid();
        MobileDetailSpecialInfoPojo mobileDetailSpecialInfoPojo = super.getMobileDetailSpecialInfo(formDataDetailDTO, paasFormDataEntityExt, explainMap);
        // 评分
        // 栗子图标
        String pid = getPid(formDataDetailDTO, corpid, paasFormDataEntityExt);
        Map<String, Object> operation = mobileDetailSpecialInfoPojo.getOperation();
        operation.put("pid", pid);
        mobileDetailSpecialInfoPojo.setOperation(operation);
        return mobileDetailSpecialInfoPojo;
    }
}
